package main

import (
	"github.com/kataras/iris/middleware/logger"
	"github.com/kataras/iris"
	"github.com/kataras/iris/middleware/recover"
	"smallstory/controllers"
	"github.com/dvsekhvalnov/jose2go"
	"encoding/json"
)

type Token struct {
	Token string `json:"token"`
	Time  int64  `json:"time"`
}

func main() {

	app := iris.New()
	// Optionally, add two built'n handlers
	// that can recover from any http-relative panics
	// and log the requests to the terminal.
	app.Use(recover.New())
	app.Use(logger.New())

	storyController := controllers.StoryController{}

	storiesRoutes := app.Party("/v1/story", tokenMiddleware)
	{
		storiesRoutes.Get("/chapter", storyController.GetChapterDetails)

		storiesRoutes.Get("/list", storyController.GetStoryList)

		storiesRoutes.Post("/chapter/create", storyController.CreateChapter)

		storiesRoutes.Post("/chapter/add", storyController.AddChapter)

		storiesRoutes.Post("/chapter/like", storyController.Like)
	}

	loginController := controllers.LoginController{}

	loginRoutes := app.Party("/v1/user", tokenMiddleware)
	{
		loginRoutes.Post("/login", loginController.Login)
	}

	// http://localhost:8080
	// http://localhost:8080/ping
	// http://localhost:8080/hello
	app.Run(iris.Addr(":8088"),
		iris.WithCharset("UTF-8"),
		iris.WithoutServerError(iris.ErrServerClosed),
		iris.WithoutVersionChecker,
		iris.WithOptimizations)

}

var key = []byte(`1987419`)

func tokenMiddleware(ctx iris.Context) {
	var token string
	if ctx.Method() != "POST" {
		ctx.Application().Logger().Infof("Path: %s | IP: %s | Params: %s", ctx.Path(), ctx.RemoteAddr(), ctx.URLParams())
		token = ctx.URLParam("token")
	} else {
		ctx.Application().Logger().Infof("Path: %s | IP: %s | Params: %s", ctx.Path(), ctx.RemoteAddr(), ctx.FormValues())
		token = ctx.FormValue("token")
	}

	//now := time.Now()
	//nowDate := now.Unix()

	if len(token) > 0 {
		payload, _, err := jose.Decode(token, key)
		ctx.Application().Logger().Infof("payload: %s", payload)
		if err == nil {
			res := Token{}
			json.Unmarshal([]byte(payload), &res)
			ctx.Next()
		} else {
			ctx.JSON(controllers.ApiResponse{Code: 400, ErrorMessage: "token is invalid"})
			panic(err)

		}

	} else {
		ctx.JSON(controllers.ApiResponse{Code: 400, ErrorMessage: "token已失效"})

	}

}
